//
//  WWComposeController.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/4/24.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit
import SVProgressHUD


class WWComposeController: UIViewController {

    let rightBarButton = UIBarButtonItem(title:"发送", imageName: "", target: self, action: #selector(sender))
    //视图即将显示
//    override func viewDidAppear(_ animated: Bool) {
//        super .viewDidAppear(animated)
//        self.textView.becomeFirstResponder() //在textview显示的时候默认选中弹出键盘
//    }
     let collection = WWPictureCollectionViewController()
    //视图已经显示
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册通知,监听弹出键盘
        NotificationCenter.default.addObserver(self, selector: #selector(addObserverKeyboard(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        view.backgroundColor = UIColor.white
        //导航栏相关
        setNavBar()
        setupUI()
    }
    //视图即将出现的的时候判断图片数量,没有就隐藏
    override func viewWillAppear(_ animated: Bool) {
        super .viewWillAppear(animated)
        self.collection.view.isHidden = collection.ArrayImages.count == 0
    }
    //搭建界面
    private func setupUI(){
        //给当前视图添加子视图控制器
        self.addChildViewController(self.collection)
        self.view.addSubview(textView)
        self.view.addSubview(collection.view)
        self.view.addSubview(stackView)//底部按钮条
        
        collection.view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        stackView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.width.equalTo(40)
        }
        for i in 0..<5 {
            let button = UIButton(type: .contactAdd)
            button.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
            button.tag = i
            self.stackView.addArrangedSubview(button)
            button.addTarget(self, action: #selector(buttonAddClick(button:)), for : .touchUpInside)
        }
        
    }
    //MARK: 监听键盘弹出
    @objc private func addObserverKeyboard (n:Notification){
//        print("--\(n)")
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        print(offsetY)
        self.stackView.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(offsetY)
        }
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
    }
    
    //底部工具条
    @objc private func buttonAddClick(button:UIButton){
        switch button.tag {
        case 0: //图片选择器
            print("按钮1")
            collection.UserWillAdd(cell: nil )
        case 1:
            print("按钮2")
        case 2:
            print("按钮3")
        case 3:
            print("按钮4")
        case 4:
            print("按钮5")
        default:
            print("未知")
        }
    }
    
    
    //close
    @objc private func colse (){
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    //发送微博
    @objc private func sender(){
        print("fa")
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        //POST请求不需要做urlEncode 只有get请求需要处理
        let parameters = ["access_token" : WWUserAccountViewModel.shared.userAccount?.access_token,
                          "status" : textView.text]
        WWNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: { (responseObject,error) -> () in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布微博失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
        })
    }
    //导航栏相关
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title:"关闭", imageName: "", target: self, action: #selector(colse))
        self.navigationItem.rightBarButtonItem = rightBarButton
        self.rightBarButton.isEnabled = false
        self.navigationItem.titleView = titleViewLabel
    }
    
    //MARK: // textView
    lazy var textView: UITextView = {
        let t = UITextView()
        t.font = UIFont.systemFont(ofSize: 18)
        t.textColor = UIColor.darkGray
        t.backgroundColor = UIColor(white: 0.9, alpha: 1)
        t.delegate = self as UITextViewDelegate
//        t.keyboardDismissMode = .onDrag
//        t.alwaysBounceVertical = true
        return t
    }()
    
    //MARK: titleView
    lazy var titleViewLabel: UILabel = {
        let label = UILabel()
        if let userName = WWUserAccountViewModel.shared.userAccount?.name{
            let titleText = "发布微博\n\(userName)"
            label.numberOfLines = 0
            label.textAlignment = .center
            label.text = titleText
            //给label添加属性文本
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 13), NSAttributedStringKey.foregroundColor : UIColor.orange], range: range)
            label.attributedText = strM
            label.sizeToFit()
        }else{
            label.text = "发布微博"
        }
        return label
    }()
    
    //MARK: stackView
    lazy var stackView: UIStackView = {
        let sta = UIStackView(frame: CGRect.zero)
        //设置方向
        sta.axis = .horizontal
        //设置填充模式
        sta.distribution = .fillEqually
//        sta.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
        return sta
    }()
    

    deinit{
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK: 委托
extension WWComposeController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.rightBarButton.isEnabled = textView.hasText
    }
}





